<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=script, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      const memoizePromise = (fn) => {
        let promise = null
        return function (...args) {
          if (!promise) {
            promise = fn(...args)
              .then((res) => {
                promise = null
                return res
              })
              .catch((err) => {
                promise = null
                return Promise.reject(err)
              })
          }
          return promise
        }
      }

      let token = null
      let requestToken = memoizePromise(() => {
        return new Promise((resolve, reject) => {
          if (token) {
            console.log('token已经存在了')
            resolve(token)
            return
          }
          setTimeout(() => {
            token = 'this is token'
            console.log('请求 token 成功一次')
            resolve(token)
          }, 1000)
        })
      })

      let request = (args) => {
        return new Promise(async (resolve, reject) => {
          try {
            let token = await requestToken()
            setTimeout(() => {
              resolve(`${args} 请求成功了，token是 ${token}`)
            }, 300)
          } catch (err) {
            reject(`${args}：请求失败了`)
          }
        })
      }
      request('getUserInfo')
        .then((res) => console.log(res))
        .catch((error) => console.error(error))
      request('getList')
        .then((res) => console.log(res))
        .catch((error) => console.error(error))
      request('getDetail')
        .then((res) => console.log(res))
        .catch((error) => console.error(error))

      // setTimeout(() => {
      //   request('getUserInfo')
      //     .then((res) => console.log(res))
      //     .catch((error) => console.error(error))
      // }, 2000)
    </script>
  </body>
</html>
